<?php

namespace yii\authclient\clients;

use yii\authclient\OAuth2;
use yii\web\HttpException;

class QQ extends OAuth2 {

    public $authUrl = 'https://graph.qq.com/oauth2.0/authorize';
    public $tokenUrl = 'https://graph.qq.com/oauth2.0/token';
    public $apiBaseUrl = 'https://graph.qq.com';

    public function init() {
        parent::init();
        if ($this->scope === NULL) {
            $this->scope = implode(',', ['get_user_info']);
        }
    }

    protected function initUserAttributes() {
        $user = $this->api('oauth2.0/me', 'GET');
        if (isset($user['error'])) {
            throw new HttpException(400, $user['error'] . ':' . $user['error_description']);
        }
        $userAttributes = $this->api('user/get_user_info', 'GET', [
            'oauth_consumer_key' => $user['client_id'],
            'openid' => $user['openid'],
        ]);
        $userAttributes['openid'] = $user['openid'];
        return $userAttributes;
    }

    protected function defaultName() {
        return 'qq';
    }

    protected function defaultTitle() {
        return 'QQ';
    }

    /**
     * Processes raw response converting it to actual data.
     * @param string $rawResponse raw response.
     * @param string $contentType response content type.
     * @throws Exception on failure.
     * @return array actual response.
     */
    protected function processResponse($rawResponse, $contentType = self::CONTENT_TYPE_AUTO) {
        if ($contentType == self::CONTENT_TYPE_AUTO) {
            if (strpos($rawResponse, "callback") === 0) {
                $lpos = strpos($rawResponse, "(");
                $rpos = strrpos($rawResponse, ")");
                $rawResponse = substr($rawResponse, $lpos + 1, $rpos - $lpos - 1);
                $rawResponse = trim($rawResponse);
                $contentType = self::CONTENT_TYPE_JSON;
            }
        }
        return parent::processResponse($rawResponse, $contentType);
    }
}